import org.apache.commons.codec.digest.DigestUtils as DU

/**
 * User for user account.
 */
class User {
	static transients = ['pass','confirmPass']
	static hasMany = [authorities: Role]

	/** Username */
	String username
	/** User Real Name*/
	String userRealName
	/** MD5 Password */
	String passwordHash = ''
	/** enabled */
	boolean enabled = true

	String email
	String pass
	String confirmPass

	public void setPass(String newPass)
	{
		pass = newPass;
		passwordHash = DU.md5Hex(newPass)
	}

	static constraints = {
		username(blank: false, unique: true)
		userRealName(blank: false)
		passwordHash(blank: true)
		enabled()
	}

	public String toString()
	{
		return username;
	}

	void validatePasswords() { 
		def isBlank = org.apache.commons.lang.StringUtils.&isBlank
		  if(isBlank(pass)) { 
		    this.errors.rejectValue("pass", "error.cannotBeBlank", "Password") 
		    } 
		  if(isBlank(confirmPass)) { 
		    this.errors.rejectValue("confirmPass", "error.cannotBeBlank", "Confirmation Password") 
		    } 

		  if(!(confirmPass == pass)) { 
		    this.errors.rejectValue("confirmPass", "error.passwordsDontMatch") 
		    } 


	}

    void validateAll() {
        validate()
        validatePasswords()
    }
}
